/**
 * 
 */
package com.mnurre.shopping.assistant;

import android.app.Activity;
import android.database.Cursor;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.SimpleCursorAdapter;
import android.widget.Spinner;
import android.widget.EditText;


/**
 * @author michael
 *
 */
public class EditProductActivity extends Activity implements OnClickListener {
	
	private static final String TAG = "EditProductActivity";
	private Spinner categoryNameSpinner;
	private EditText productNameEditText;
	private EditText descriptionEditText;
	private EditText priceEditText;
	private EditText barcodeEditText;
	private Button saveProductButton;
	private ProductsData mData;
	private CategoriesData mCategoriesData; // used to populate the spinner with available categories
//	private Long mListId;
	private Long mProductId;
	private Long mSelectedCategoryId;
	
	/* (non-Javadoc)
	 * @see android.app.Activity#onCreate(android.os.Bundle)
	 */
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		Log.d(TAG, "Creating activity.");
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_edit_product);
		
		Log.d(TAG, "Getting reference to UI components.");
		categoryNameSpinner = (Spinner)findViewById(R.id.categoryNameSpinner);
		
		productNameEditText = (EditText)findViewById(R.id.productNameEditText);
		descriptionEditText = (EditText)findViewById(R.id.descriptionEditText);
		priceEditText = (EditText)findViewById(R.id.priceEditText);
		barcodeEditText = (EditText)findViewById(R.id.barcodeEditText);
		saveProductButton = (Button)findViewById(R.id.saveProductButton);
		saveProductButton.setOnClickListener(this);
		
		Log.d(TAG, "Creating a new instance of ProductsData class.");
		mData = new ProductsData(this);
		
		Log.d(TAG, "Caling populateCategoriesSpinner.");
		populateCategoriesSpinner();
		
		Log.d(TAG, "Checking extras to see if we are editing.");
		Bundle extras = getIntent().getExtras();
		if(extras != null) {
			setTitle(R.string.product_edit_activity_label);
			mProductId = extras.getLong(DataManager.Tables.Products.COLUMN_ID);
			if(mProductId == 0L){
				mProductId = null;
				populateFields(extras);
				return;
			}
			// mSelectedCategoryId = extras.getLong(DataManager.Tables.Products.COLUMN_CATEGORY_ID);
			Log.d(TAG, "ProductId is " + mProductId);
			Log.d(TAG, "Calling populateFields().");
			populateFields();
		} else {
			Log.d(TAG, "We are not editing, but adding.");
			setTitle(R.string.product_add_activity_label);
			mProductId = null;
		}
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		Log.d(TAG, "Handling the button's click event. Getting product, description and price.");
		String productName = productNameEditText.getText().toString();
		Log.d(TAG, "Product Name is " + productName);
		String description = descriptionEditText.getText().toString();
		Log.d(TAG, "Description is " + description);
		Double price = Double.valueOf(priceEditText.getText().toString());
		Log.d(TAG, "Price is " + price);
		String barcode = barcodeEditText.getText().toString();
		Log.d(TAG, "Barcode is " + barcode);
		mData = new ProductsData(this);
		mData.open();
		if(mProductId == null){
			Log.d(TAG, "Adding a new product.");
			// we are adding
			mData.insertProduct(mSelectedCategoryId, productName, description, price, barcode);
		} else {
			Log.d(TAG, "Editing a product.");
			// we are editing
			mData.updateProduct(mProductId, mSelectedCategoryId, productName, description, price, barcode);
		}
		Log.d(TAG, "Closing ProductData and setting result to RESULT_OK");
		mData.close();
		setResult(RESULT_OK);
		Log.d(TAG, "Calling finish()");
		finish();
	}
	
	private void populateCategoriesSpinner(){
		Log.d(TAG, "populateCategoriesSpinner called. Creating a new CategoresData.");
		CategoriesData mCategoriesData = new CategoriesData(this);
		// populate the spinner control with the available categories
		Log.d(TAG, "Opening categories data and getting a cursor.");
		mCategoriesData.open();
		Cursor categoriesCursor = mCategoriesData.getCategories();
		startManagingCursor(categoriesCursor);
		Log.d(TAG, "Creating from array.");
		String[] from = new String[] { DataManager.Tables.Categories.COLUMN_NAME };
		Log.d(TAG, "Creating to array.");
		int[] to = new int[] { android.R.id.text1 };
		Log.d(TAG, "Creating a SimpleCursorAdapter to handle the data.");
		SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, android.R.layout.simple_spinner_item,
				categoriesCursor, from, to );
		Log.d(TAG, "Setting the drop down view resource.");
		adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		Log.d(TAG, "Setting the spinner adapter.");
		categoryNameSpinner.setAdapter(adapter);
		Log.d(TAG, "Setting the item selected listener.");
		categoryNameSpinner.setOnItemSelectedListener(
				new AdapterView.OnItemSelectedListener() {

					@Override
					public void onItemSelected(AdapterView<?> arg0, View arg1,
							int arg2, long arg3) {
						// TODO Auto-generated method stub
						Log.d(TAG, "Handling the spinner's on item selected event. The selected item's _id is " + arg3);
						mSelectedCategoryId = arg3;
					}

					@Override
					public void onNothingSelected(AdapterView<?> arg0) {
						// TODO Auto-generated method stub
					}
					
				});
		mCategoriesData.close();
	}
	
	private void populateFields(Bundle bundle){
		Log.d(TAG, "Resetting mSelectedCategoryId");
		// mSelectedCategoryId = 0L;
		
		Log.d(TAG, "Populating the fields from the returned bundle.");
		productNameEditText.setText(bundle.getString(DataManager.Tables.Products.COLUMN_NAME));
		
		Log.d(TAG, "Product Name: " + productNameEditText.getText());
		descriptionEditText.setText(bundle.getString(DataManager.Tables.Products.COLUMN_DESCRIPTION));
		
		Log.d(TAG, "Description: " + descriptionEditText.getText());
		barcodeEditText.setText(bundle.getString(DataManager.Tables.Products.COLUMN_BARCODE));
		
		Log.d(TAG, "Barcode: " + barcodeEditText.getText());
		String category = bundle.getString(DataManager.Tables.Products.COLUMN_CATEGORY);
		
		Log.d(TAG, "Category: " + category);
		// check categories to see if it's available
		Log.d(TAG, "Calling CategoriesData and getting all categories");
		CategoriesData data = new CategoriesData(this);
		
		data.open();
		Cursor cursor = data.getCategories();
		
		Log.d(TAG, "calling startManagingCursor");
		startManagingCursor(cursor);
		if(cursor == null)
		{
			Log.d(TAG, "Cursor was null. Closing data and returning.");
			data.close();
			return;
		}
		Log.d(TAG, "Checking existing categories for " + category);
		boolean hasCategory = false;
		if(category.length() > 0) do{
			if(cursor.getString(cursor.getColumnIndex(DataManager.Tables.Categories.COLUMN_NAME)) == category){
				Log.d(TAG, "We found our category.");
				hasCategory = true;
				break;
			}
		}while(cursor.moveToNext());
		if(!hasCategory && category.length() > 0){
			Log.d(TAG, "Category not found. Adding it.");
			data.insertCategory(category, 1);
		}
		data.close();
		
		if(!(category.length() > 0)) return;
		
		Log.d(TAG, "Setting the category.");
		SimpleCursorAdapter adapter = (SimpleCursorAdapter)categoryNameSpinner.getAdapter();
		Cursor spinnerCursor = adapter.getCursor();
		int max = spinnerCursor.getCount();
		if(!spinnerCursor.moveToFirst()){
			Log.e(TAG, "There are no categories? Returning");
			return;
		}
		Log.d(TAG, "Initializing position to 0");
		int position = 0;
//		do{
//			if(spinnerCursor.getString(spinnerCursor.getColumnIndex(DataManager.Tables.Categories.COLUMN_NAME)).equalsIgnoreCase(category)){
//				Log.d(TAG, "We have a matched category at position " + position);
//				mSelectedCategoryId = spinnerCursor.getLong(spinnerCursor.getColumnIndex(DataManager.Tables.Categories.COLUMN_ID));
//				Log.d(TAG, "SelectedCategoryId set to " + mSelectedCategoryId);
//				break;
//			}
//			position++;
//		}while(spinnerCursor.moveToNext());
		
		while(spinnerCursor.moveToNext()){
			if(spinnerCursor.getString(spinnerCursor.getColumnIndex(DataManager.Tables.Categories.COLUMN_NAME)).equalsIgnoreCase(category)){
				mSelectedCategoryId = spinnerCursor.getLong(spinnerCursor.getColumnIndex(DataManager.Tables.Categories.COLUMN_ID));
				Log.d(TAG, "SelectedCategoryId set to " + mSelectedCategoryId);
				break;
			}
			position++;
		}
		
		position = position >= max ? max : position;
		Log.d(TAG, "Position for selected category set to " + position + " in the category cursor.");
		categoryNameSpinner.setSelection(position);
	}
	
	private void populateFields(){
		Log.d(TAG, "populateFields called. Opening data.");
		mData.open();
		Log.d(TAG, "Getting cursor.");
		Cursor cursor = mData.getProductById(mProductId);
		Log.d(TAG, "Calling startManagingCursor.");
		startManagingCursor(cursor);
		Log.d(TAG, "Setting productNameEditText.");
		productNameEditText.setText(cursor.getString(cursor.getColumnIndex(DataManager.Tables.Products.COLUMN_NAME)));
		Log.d(TAG, "Setting product description.");
		descriptionEditText.setText(cursor.getString(cursor.getColumnIndex(DataManager.Tables.Products.COLUMN_DESCRIPTION)));
		Log.d(TAG, "Setting price.");
		priceEditText.setText(cursor.getString(cursor.getColumnIndex(DataManager.Tables.Products.COLUMN_PRICE)));
		Log.d(TAG, "Setting barcode.");
		barcodeEditText.setText(cursor.getString(cursor.getColumnIndex(DataManager.Tables.Products.COLUMN_BARCODE)));
		Log.d(TAG, "Setting the category name.");
		String category = cursor.getString(cursor.getColumnIndex(DataManager.Tables.Products.COLUMN_CATEGORY));
		mData.close();
		Log.d(TAG, "Setting the category.");
		SimpleCursorAdapter adapter = (SimpleCursorAdapter)categoryNameSpinner.getAdapter();
		Cursor spinnerCursor = adapter.getCursor();
		spinnerCursor.moveToFirst();
		int position = 0;
		do{
			if(spinnerCursor.getString(spinnerCursor.getColumnIndex(DataManager.Tables.Categories.COLUMN_NAME)).equalsIgnoreCase(category)){
				mSelectedCategoryId = spinnerCursor.getLong(spinnerCursor.getColumnIndex(DataManager.Tables.Categories.COLUMN_ID));
				Log.d(TAG, "SelectedCategoryId set to " + mSelectedCategoryId);
				break;
			}
			position++;
		}while(spinnerCursor.moveToNext());
		Log.d(TAG, "Position for selected category set to " + position + " in the category cursor.");
		categoryNameSpinner.setSelection(position);
	}
	
}
